﻿// --- START OF FILE HVACLoadItemViewModel.cs ---

using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Analysis; // HVACLoadSpaceType
using Autodesk.Revit.DB.Mechanical; // 需要 OutdoorAirMethod (如果存在)
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Globalization; // CultureInfo
using System.Diagnostics;

namespace RevitProject.SpaceManager.ViewModel.HAVCLoadViewModelPart
{
    public partial class HVACLoadItemViewModel : ObservableObject
    {
        private readonly HVACLoadSpaceType _spaceType;
        private readonly Document _doc;
        private bool _isSelected;

        private readonly ElementId _cachedId; 

        public event EventHandler IsSelectedChanged; // 添加事件
        /// <summary>
        /// 指示该空间类型在 DataGrid 中是否被选中。
        /// </summary>
        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                if (SetProperty(ref _isSelected, value))
                {
                    IsSelectedChanged?.Invoke(this, EventArgs.Empty); // 触发事件
                }
            }
        }
        public ElementId Id => _cachedId; // <-- 直接返回缓存的 ID
        /// <summary>
        /// 获取空间类型的名称。如果对象无效，返回带标记的名称。
        /// </summary>
        public string Name
        {
            get
            {
                try
                {
                    // 优先检查 IsValidObject
                    if (_spaceType != null && _spaceType.IsValidObject)
                    {
                        return _spaceType.Name ?? "无效名称";
                    }
                }
                catch (Autodesk.Revit.Exceptions.InvalidObjectException)
                {
                    // 捕获可能的异常（理论上 IsValidObject 应该能避免，但作为保险）
                }
                // 如果对象无效或访问出错，返回带标记的缓存名称（如果需要）或固定文本
                // 可以考虑缓存 Name，但简单起见先返回固定文本
                return "(对象已失效)";
            }
        }
        // --- 属性访问  ---

        public string IsPlenumDisplay => IsValid() ? (_spaceType.IsPlenum ? "是" : "否") : "N/A";
        public string AreaPerPersonDisplay => IsValid() ? GetFormattedValue(_spaceType.AreaPerPerson, UnitTypeId.SquareMeters, "F2", 1e-9) : "N/A";
        public string LightingLoadDensityDisplay => IsValid() ? GetFormattedValue(_spaceType.LightingLoadDensity, UnitTypeId.WattsPerSquareMeter, "F2") : "N/A";
        
        public string PowerLoadDensityDisplay => IsValid() ? GetFormattedValue(_spaceType.PowerLoadDensity, UnitTypeId.WattsPerSquareMeter, "F2") : "N/A";
        public string SensibleHeatGainPerPersonDisplay => IsValid() ? GetFormattedValue(_spaceType.SensibleHeatGainPerPerson, UnitTypeId.Watts, "F1") : "N/A";
        public string LatentHeatGainPerPersonDisplay => IsValid() ? GetFormattedValue(_spaceType.LatentHeatGainPerPerson, UnitTypeId.Watts, "F1") : "N/A";
        public string HeatingSetpointDisplay => IsValid() ? GetFormattedValue(_spaceType.HeatingSetPoint, UnitTypeId.Celsius, "F1") : "N/A";
        public string CoolingSetpointDisplay => IsValid() ? GetFormattedValue(_spaceType.CoolingSetPoint, UnitTypeId.Celsius, "F1") : "N/A";
        public string HumidificationSetpointDisplay => IsValid() ? GetFormattedValue(_spaceType.HumidificationSetPoint, UnitTypeId.Percentage, "F1") : "N/A";
        public string DehumidificationSetpointDisplay => IsValid() ? GetFormattedValue(_spaceType.DehumidificationSetPoint, UnitTypeId.Percentage, "F1") : "N/A";
        public string InfiltrationAirflowPerAreaDisplay
        {
            get
            {
                if (!IsValid()) return "N/A";
                try
                {
                    Parameter param = _spaceType.get_Parameter(BuiltInParameter.SPACE_INFILTRATION_PARAM);
                    return GetFormattedValue(param?.AsDouble(), UnitTypeId.LitersPerSecondSquareMeter, "F2");
                }
                catch (Autodesk.Revit.Exceptions.InvalidObjectException) { return "N/A"; } // 添加 try-catch
            }
        }
        public string OccupancyScheduleDisplay => IsValid() ? GetScheduleName(_spaceType.get_Parameter(BuiltInParameter.SPACE_OCCUPANCY_SCHEDULE_PARAM)?.AsElementId()) : "N/A";
        public string LightingScheduleDisplay => IsValid() ? GetScheduleName(_spaceType.get_Parameter(BuiltInParameter.SPACE_LIGHTING_SCHEDULE_PARAM)?.AsElementId()) : "N/A";
        public string PowerScheduleDisplay => IsValid() ? GetScheduleName(_spaceType.get_Parameter(BuiltInParameter.SPACE_POWER_SCHEDULE_PARAM)?.AsElementId()) : "N/A";
        public string OutsideAirPerPersonDisplay => IsValid() ? GetFormattedValue(_spaceType.OutdoorAirPerPerson, UnitTypeId.CubicMetersPerHour, "F2") : "N/A";
        public string OutsideAirPerAreaDisplay => IsValid() ? GetFormattedValue(_spaceType.OutdoorAirPerArea, UnitTypeId.LitersPerSecondSquareMeter, "F2") : "N/A";
        public string AirChangesPerHourDisplay => IsValid() ? GetFormattedValue(_spaceType.AirChangesPerHour, null, "F2") : "N/A";

        //父分类
        public string ParentCategoryName { get; private set; }

        
        // 新风方法: 使用 OutdoorAirFlowStandard 属性并进行映射
        public string OutsideAirMethodDisplay
        {
            get
            {
                if (!IsValid()) return "N/A"; // 先检查有效性
                if (_spaceType == null) return "N/A";
                try
                {
                    // 直接访问属性，类型是 OutdoorAirFlowStandard
                    OutdoorAirFlowStandard standard = _spaceType.OutdoorAirFlowStandard;

                    // 将枚举值映射为更友好的中文字符串
                    switch (standard)
                    {
                        // *** 根据你找到的实际枚举成员名称进行映射 ***
                        case OutdoorAirFlowStandard.ByPeopleAndByArea:
                            return "按人数和面积"; // 或者 "组合 (人+面积)"
                        case OutdoorAirFlowStandard.ByACH: // API 枚举成员通常是大写开头，确认一下
                            return "按换气次数";
                        case OutdoorAirFlowStandard.MaxByPeople_ByArea: // 猜测 Max(by People, by Area) 对应的枚举
                            return "最大值 (按人数, 按面积)";
                        case OutdoorAirFlowStandard.MaxByACH_ByPeopleByArea: // 猜测 Max(by ACH, by People and by Area) 对应的枚举
                            return "最大值 (按换气次数, 按人数和面积)";
                        case OutdoorAirFlowStandard.MaxByACH_ByArea_ByPeople: // 猜测 Max(by ACH, by Area, by People) 对应的枚举
                            return "最大值 (按换气次数, 按面积, 按人数)";
                        // case OutdoorAirFlowStandard.None: // 检查是否有 "无" 或类似选项
                        //     return "无";
                        default:
                            // 如果有其他未知的枚举值，直接显示其英文名称
                            Debug.WriteLine($"未知的 OutdoorAirFlowStandard 值: {standard}");
                            return standard.ToString();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"获取 OutdoorAirFlowStandard 时出错: {ex.Message}");
                    return "错误";
                }
            }
        }
        /// <summary>
        /// 检查内部 Revit 对象是否仍然有效。
        /// </summary>
        /// <returns>如果对象有效则返回 true，否则返回 false。</returns>
        private bool IsValid()
        {
            // 添加 null 检查和 IsValidObject 检查
            return _spaceType != null && _spaceType.IsValidObject;
        }

        // 构造函数
        public HVACLoadItemViewModel(HVACLoadSpaceType spaceType, string parentCategoryName)
        {
            if (spaceType == null || !spaceType.IsValidObject) throw new ArgumentNullException(nameof(spaceType));
            _spaceType = spaceType;
            _doc = spaceType.Document;
            _cachedId = spaceType.Id; // <-- 在构造时缓存 ID

            ParentCategoryName = parentCategoryName ?? "(未分类)"; // 如果传入 null，显示未分类
            IsSelected = false; // 初始化选中状态

            OnPropertyChanged(string.Empty);
        }

      
        // 辅助方法：获取内部值，进行单位转换并格式化为字符串
        private string GetFormattedValue(double? internalValue, ForgeTypeId displayUnitTypeId, string format, double zeroThreshold = 0.0)
        {
            if (!internalValue.HasValue) return "N/A";
            try
            {
                double value = internalValue.Value;
                if (zeroThreshold > 0.0 && Math.Abs(value) < zeroThreshold)
                {
                    return 0.0.ToString(format, CultureInfo.InvariantCulture);
                }
                if (displayUnitTypeId == null || string.IsNullOrEmpty(displayUnitTypeId.TypeId))
                {
                    return value.ToString(format, CultureInfo.InvariantCulture);
                }
                double displayValue = UnitUtils.ConvertFromInternalUnits(value, displayUnitTypeId);
                return displayValue.ToString(format, CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"单位转换/格式化错误 for Value '{internalValue}' to Unit '{displayUnitTypeId?.TypeId ?? "null"}': {ex.Message}");
                return "错误";
            }
        }
        // 辅助方法：获取明细表名称
        private string GetScheduleName(ElementId scheduleId)
        {
            if (_doc == null || scheduleId == null || scheduleId == ElementId.InvalidElementId) return "无";
            try
            {
                var schedule = _doc.GetElement(scheduleId);
                return schedule?.Name ?? "无效 ID";
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"获取明细表名称时出错 (ID: {scheduleId}): {ex.Message}");
                return "错误";
            }
        }
        public override bool Equals(object obj) { return obj is HVACLoadItemViewModel model && _cachedId == model._cachedId;; }
        public override int GetHashCode() { return _cachedId?.Value.GetHashCode() ?? 0; }
    }
}
// --- END OF FILE HVACLoadItemViewModel.cs ---